from django.shortcuts import render
from decimal import Decimal
from rest_framework.response import Response
from . serializers import OrderSettlementSerializer, SaveOrderSerializer
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated

from django_redis import get_redis_connection

# Create your views here.
from rest_framework.views import APIView

from goods.models import SKU


class OrderSettlementView(APIView):
    '''订单结算'''
    def get(self, request):
        # 获取用户的身份 user
        user = request.user

        # 从redis获取购物车数据 sku_id count selected
        redis_conn = get_redis_connection('cart')

        # 获取商品的数量
        redis_cart_dict = redis_conn.hgetall('cart_%s' % user.id)

        # 获取勾选的商品信息
        redis_cart_selected = redis_conn.smembers('cart_selected_%s' % user.id)

        cart = {}

        for sku_id in redis_cart_selected:
            cart[int(sku_id)] = int(redis_cart_dict[sku_id])

        # 查询数据库 获取商品详细信息
        sku_obj_list = SKU.objects.filter(id__in=cart.keys())

        # 遍历sku对象列表 向sku对象中添加count属性
        for sku in sku_obj_list:
            sku.count = cart[sku.id]

        # 运费
        freight = Decimal('10.00')

        # 序列化返回
        serializer = OrderSettlementSerializer({'freight': freight, 'skus': sku_obj_list})
        return Response(serializer.data)

class SaveOrderView(CreateAPIView):
    '''保存订单'''
    serializer_class = SaveOrderSerializer
    permission_classes = [IsAuthenticated]